package com.uphone.kingmall.main;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.google.gson.JsonSyntaxException;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.CricleCatListActivity;
import com.uphone.kingmall.activity.CricleMoreActivity;
import com.uphone.kingmall.activity.CricleShopsListActivity;
import com.uphone.kingmall.activity.GoodsDetailActivity;
import com.uphone.kingmall.activity.ShopDetailActivity;
import com.uphone.kingmall.activity.personal.ShangJiaRuZhuActivity;
import com.uphone.kingmall.activity.personal.ShangJiaRuZhuSuccessActivity;
import com.uphone.kingmall.activity.personal.VipBuyActivity;
import com.uphone.kingmall.activity.personal.VipUpgradeActivity;
import com.uphone.kingmall.adapter.ClassFenLeiAdapter;
import com.uphone.kingmall.adapter.CricleIndexShopAdapter;
import com.uphone.kingmall.base.BaseFragment;
import com.uphone.kingmall.bean.AdvertsBean;
import com.uphone.kingmall.bean.CircleIndexShopBean;
import com.uphone.kingmall.bean.GetShopStatusBean;
import com.uphone.kingmall.bean.IndexCatsList;
import com.uphone.kingmall.bean.UserInfosBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GlideRoundTransform;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.RecycleViewDivider;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.intent.IntentUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : SuMeng
 * e-mail : 986335838@qq.com
 * time   : 2019/02/15
 * desc   : 商圈fragment
 */
public class CricleFragment extends BaseFragment implements AMapLocationListener {
    @BindView(R.id.iv_guanggao1)
    ImageView ivGuanggao1;
    @BindView(R.id.iv_guanggao2)
    ImageView ivGuanggao2;
    @BindView(R.id.iv_guanggao3)
    ImageView ivGuanggao3;
    @BindView(R.id.rv_cricle)
    RecyclerView rvcricle;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.rv_list2)
    RecyclerView rvList2;
    @BindView(R.id.rv_list3)
    RecyclerView rvList3;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.shop_cart_refresh)
    SwipeRefreshLayout shopCartRefresh;
    private ClassFenLeiAdapter homeCricleAdapter;
    private ArrayList<IndexCatsList.CatsBean> catsList;
    private CricleIndexShopAdapter indexShopAdapter;
    private CricleIndexShopAdapter indexShopAdapter2;
    private CricleIndexShopAdapter indexShopAdapter3;
    private LatLng latLng;
    private String city = "";
    private String province;
    private String defaultDistrict;
    private String locationCity;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_fragment_cricle;
    }

//    public void reload(city){
//        tvCity.setText(city + "");
//        loadData
//    }

    @Override
    public void initData() {
        initRv();
        shopCartRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shopCartRefresh.setRefreshing(false);
                    }
                }, 2000);
                loadData();
            }
        });
        loadData();
    }

    private void initRv() {
        rvcricle.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        rvcricle.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.HORIZONTAL, 10, getResources().getColor(R.color.colorBg)));
        homeCricleAdapter = new ClassFenLeiAdapter();
        rvcricle.setAdapter(homeCricleAdapter);
        homeCricleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == catsList.size() - 1) {
                    //更多
                    CommonUtil.startIntent(getActivity(), CricleMoreActivity.class);
                    return;
                }
                IntentUtils.getInstance().with(getActivity(), CricleCatListActivity.class)
                        .putInt(ConstansUtils.ID, catsList.get(position).getId())
                        .putString(ConstansUtils.TITLE, catsList.get(position).getCatName())
                        .putString(ConstansUtils.URL, MyUrl.getCatShops).start();
            }
        });


        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        indexShopAdapter = new CricleIndexShopAdapter();
        rvList.setAdapter(indexShopAdapter);
        rvList2.setLayoutManager(new LinearLayoutManager(getContext()));
        indexShopAdapter2 = new CricleIndexShopAdapter();
        rvList2.setAdapter(indexShopAdapter2);
        rvList3.setLayoutManager(new LinearLayoutManager(getContext()));
        indexShopAdapter3 = new CricleIndexShopAdapter();
        rvList3.setAdapter(indexShopAdapter3);


        CricleIndexShopAdapter.CircleIndexShopClickListener listener = new CricleIndexShopAdapter.CircleIndexShopClickListener() {
            @Override
            public void moreClick(View v, int position, CircleIndexShopBean.DataBean item) {
                // 查看更多
                CommonUtil.startIntent(getActivity(), CricleShopsListActivity.class, item.getCircleType());
            }

            @Override
            public void itemChildClick(View v, int position, int childPosition, CircleIndexShopBean.DataBean item, CircleIndexShopBean.DataBean.ShopsBean childItem) {
                CommonUtil.startIntent(getActivity(), ShopDetailActivity.class, childItem.getShopId());
            }
        };
        indexShopAdapter.setItemClickListener(listener);
        indexShopAdapter2.setItemClickListener(listener);
        indexShopAdapter3.setItemClickListener(listener);
    }

    private void loadData() {

        loadBannerData(4);
        loadBannerData(5);
        loadBannerData(6);
        // 一级分类
        initFenLei();
        // 分类下的商铺列表
        initShopList();
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    private void loadBannerData(final int type) {
        HttpParams params = new HttpParams();
        params.put("type", type + "");
        OkGoUtils.normalRequest(MyUrl.adverts, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final AdvertsBean bean = GsonUtils.getGson().fromJson(body, AdvertsBean.class);
                if (bean.getCode() == 0) {
                    if (bean.getAds() != null && bean.getAds().size() > 0) {
                        switch (type) {
                            case 4:
                                advertImage(type, ivGuanggao1, bean.getAds().get(0));
                                break;
                            case 5:
                                advertImage(type, ivGuanggao2, bean.getAds().get(0));
                                break;
                            case 6:
                                advertImage(type, ivGuanggao3, bean.getAds().get(0));
                                break;
                        }
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });
    }

    private void advertImage(final int type, ImageView iv, final AdvertsBean.AdsBean adsBean) {
//        GlideUtils.getInstance().loadCornerImage(getActivity(), adsBean.getAdImg(), SizeUtils.dp2px(8), iv);

        RoundedCorners roundedCorners = new RoundedCorners(SizeUtils.dp2px(8));
        RequestOptions requestOptions = RequestOptions
                .bitmapTransform(roundedCorners)
                .placeholder(R.mipmap.img_default_wz)
                .error(R.mipmap.img_default_wz)
                .transform(new GlideRoundTransform(getActivity(), SizeUtils.dp2px(8)));
        GlideUtils.getInstance().loadImage(getActivity(), adsBean.getAdImg(), iv, requestOptions);


        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 6) {
                    if (CommonUtil.checkLogin()) {
                        OkGoUtils.normalRequest(MyUrl.getUserInfo, null, new onNormalRequestListener() {
                            @Override
                            public void onSuccess(String body, int code) {
                                if (code == 0) {
                                    try {
                                        UserInfosBean bean = GsonUtils.getGson().fromJson(body, UserInfosBean.class);
                                        UserInfosBean.UserInfoBean user = bean.getUserInfo();
                                        if (user != null) {
                                            int shopStatusInt = user.getShopStatus();
                                            if (shopStatusInt == 1) {
                                                //商家已入驻
                                                CommonUtil.startIntent(getActivity(), ShangJiaRuZhuSuccessActivity.class);
                                            } else {
                                                GetShopStatus(user);
                                            }
                                        } else {
                                        }
                                    } catch (JsonSyntaxException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {

                            }
                        });
                    }
                    return;
                }
                if (adsBean.getGoodsId() > 0) {
                    IntentUtils.getInstance()
                            .with(getActivity(), GoodsDetailActivity.class)
                            .putInt(ConstansUtils.ID, adsBean.getGoodsId())
                            .start();
                }
            }
        });
    }

    private void GetShopStatus(final UserInfosBean.UserInfoBean user) {
        OkGoUtils.normalRequestGet(MyUrl.GetShopStatus, new onNormalRequestListener() {
            @Override
            public void onSuccess(String json, int code) {
                if (code == 0) {
                    GetShopStatusBean bean = GsonUtils.getGson().fromJson(json, GetShopStatusBean.class);
                    if (bean.getCode() == 0) {
                        if (bean.getData().getShopStatus() == 1) {
                            openActivity(ShangJiaRuZhuSuccessActivity.class);
                        } else if (bean.getData().getShopStatus() == 4) {
                            if (user.getUserType() == 2) {
                                if (user.getWay() == 1) {
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("type", 3);
                                    openActivity(VipUpgradeActivity.class, bundle);
                                } else {
                                    openActivity(VipUpgradeActivity.class);
                                }
                            } else {
                                openActivity(ShangJiaRuZhuActivity.class);
                            }
                        } else {
                            openActivity(ShangJiaRuZhuActivity.class);
                        }
                    } else if (bean.getCode() == 101 || bean.getCode() == 102) {
                        if (user.getWay() == 0) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", 3);
                            openActivity(VipBuyActivity.class, bundle);
                        } else if (user.getWay() == 1) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", 3);
                            openActivity(VipUpgradeActivity.class, bundle);
                        } else {
                            openActivity(VipUpgradeActivity.class);
                        }
                    }

                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }


    private void initShopList() {
        HttpParams params = new HttpParams();
        params.put("limit", "100");
        params.put("orderby", "1");
        params.put("asc", "2");
        if (latLng != null) {
            params.put("lonlat", latLng.longitude + "," + latLng.latitude);
        }
        LogUtils.e("SharedPreferencesHelper.getCity:" + SharedPreferencesHelper.getCity());
        if (!TextUtils.isEmpty(SharedPreferencesHelper.getCity())) {
            city = SharedPreferencesHelper.getCity();
        }
        params.put("city", city);
        OkGoUtils.normalRequest(MyUrl.getCircleIndexShops, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                CircleIndexShopBean bean = GsonUtils.getGson().fromJson(body, CircleIndexShopBean.class);
                if (bean.getCode() == 0) {
                    List<CircleIndexShopBean.DataBean> dataList = new ArrayList<>();
                    List<CircleIndexShopBean.DataBean> dataList2 = new ArrayList<>();
                    List<CircleIndexShopBean.DataBean> dataList3 = new ArrayList<>();
                    if (bean.getData() != null && bean.getData().size() > 0) {
                        for (int i = 0; i < bean.getData().size(); i++) {
                            if (i <= 3) {
                                dataList.add(bean.getData().get(i));
                            } else if ((i <= 8)) {
                                dataList2.add(bean.getData().get(i));
                            } else {
                                dataList3.add(bean.getData().get(i));
                            }
                        }
                    }
                    indexShopAdapter.setNewData(dataList);
                    indexShopAdapter2.setNewData(dataList2);
                    indexShopAdapter3.setNewData(dataList3);
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });

    }


    /**
     * 初始化分类
     */
    private void initFenLei() {

        OkGoUtils.normalRequest(MyUrl.getBusicircleCats, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final IndexCatsList catsListBean = GsonUtils.getGson().fromJson(body, IndexCatsList.class);
                if (catsListBean.getCode() == 0) {
                    if (catsList == null) {
                        catsList = new ArrayList<>();
                    }
                    catsList.clear();
                    if (catsListBean.getCats() != null) {
                        catsList.addAll(CommonUtil.getList(catsListBean.getCats(), 9));
                    }
                    catsList.add(new IndexCatsList.CatsBean("更多"));
                    homeCricleAdapter.setNewData(catsList);
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });


    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private static final int PERMISSION_REQUEST_MY_REQUEST = 3;

    private void loadPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_SETTINGS);
            }
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (!permissionList.isEmpty()) {  //申请的集合不为空时，表示有需要申请的权限
                requestPermissions(permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQUEST_MY_REQUEST);
            } else { //所有的权限都已经授权过了
                initLocation();
            }
        } else {
            initLocation();
        }

    }

    /**
     * 如果AMapLocationClient是在当前Activity实例化的，
     * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            if (requestCode == PERMISSION_REQUEST_MY_REQUEST) {
                // 定位权限
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有开启定位权限，定位失败");
                    DialogUtil.openAppDetails(getActivity(), "定位");
                }
            }
        }
    }

    @Override
    public void initView(View view) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Date d = new Date();
        String str = sdf.format(d);
        tvDate.setText(str + "");
        SharedPreferencesHelper.saveCity("");
        loadPermission();
        mCityPickerView.init(getActivity());
    }

    @OnClick({R.id.iv_guanggao1, R.id.iv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_guanggao1:
                break;
            case R.id.iv_location:
//                citySeletor();
                mWheelType = CityConfig.WheelType.PRO_CITY_DIS;
                wheel();
                break;
        }
    }

    public CityConfig.WheelType mWheelType = CityConfig.WheelType.PRO_CITY_DIS;

    CityPickerView mCityPickerView = new CityPickerView();


    /**
     * 弹出选择器
     */
    private void wheel() {


        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")
                .visibleItemsCount(5)
                .province(province)
                .city(city)
                .district(defaultDistrict)
                .provinceCyclic(true)
                .cityCyclic(true)
                .districtCyclic(true)
                .setCityWheelType(mWheelType)
                .setCustomItemLayout(R.layout.kingmall_item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)
                .setShowGAT(true)
                .build();

        mCityPickerView.setConfig(cityConfig);
        mCityPickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, com.lljjcoder.bean.CityBean citybean, DistrictBean district) {
//                StringBuilder sb = new StringBuilder();
//                sb.append("选择的结果：\n");
//                if (province != null) {
//                    sb.append(province.getName() + " " + province.getId() + "\n");
//                }
//
//                if (citybean != null) {
//                    sb.append(citybean.getName() + " " + citybean.getId() + ("\n"));
//                }
//
//                if (district != null) {
//                    sb.append(district.getName() + " " + district.getId() + ("\n"));
//                }
                city = citybean.getName() + district.getName();
                tvCity.setText(city + "");
                SharedPreferencesHelper.saveCity(city);
                loadData();
            }

            @Override
            public void onCancel() {
//                ToastUtils.showLongToast(CitypickerWheelActivity.this, "已取消");
            }
        });
        mCityPickerView.showCityPicker();
    }


//    private void citySeletor() {
//        CityPicker.from(this)
//                .enableAnimation(true)
//                .setAnimationStyle(R.style.DefaultCityPickerAnimation)
//                .setLocatedCity(new LocatedCity(locationCity, province, ""))
////                        .setHotCities(hotCities)
//                .setOnPickListener(new OnPickListener() {
//                    @Override
//                    public void onPick(int position, City data) {
//                        KeyboardUtils.hideSoftInput(getActivity());
//                        if (!TextUtils.isEmpty(data.getName())) {
//                            city = data.getName();
//                            tvCity.setText(city + "");
//                            SharedPreferencesHelper.saveCity(city);
//                            loadData();
//                        }
//                    }
//
//                    @Override
//                    public void onCancel() {
//                        KeyboardUtils.hideSoftInput(getActivity());
//                    }
//
//                    @Override
//                    public void onLocate() {
//                    }
//                }).show();
//    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                if (!TextUtils.isEmpty(aMapLocation.getCity())) {
                    city = aMapLocation.getCity() + aMapLocation.getDistrict();
                    locationCity = city;
                    defaultDistrict = aMapLocation.getDistrict();
                    LogUtils.e("定位：" + city);
                    province = aMapLocation.getProvince();
                    tvCity.setText(city);
                    SharedPreferencesHelper.saveCity(city);
                }
                mLocationClient.stopLocation();
                loadData();
            }
        } else {
            LogUtils.e("定位失败");
            tvCity.setText("定位失败");
        }
    }
}
